<template>
  <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑医院' : '新增医院'"
      width="500px"
      :close-on-click-modal="false"
      @close="handleClose"
  >
    <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="80px"
    >
      <el-form-item label="医院名称" prop="name">
        <el-input
            v-model="formData.name"
            placeholder="请输入医院名称"
            clearable
            maxlength="50"
            show-word-limit
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
            type="primary"
            :loading="loading"
            @click="handleSubmit"
        >
          {{ loading ? '保存中...' : '确定' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { hospitalApi } from '../api/hospital'

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  hospitalData: {
    type: Object,
    default: () => ({})
  },
  isEdit: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['update:visible', 'success'])

// 响应式数据
const dialogVisible = ref(false)
const loading = ref(false)
const formRef = ref()

// 表单数据
const formData = reactive({
  name: ''
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入医院名称', trigger: 'blur' },
    { min: 2, max: 50, message: '医院名称长度在 2 到 50 个字符', trigger: 'blur' }
  ]
}

// 监听visible变化
watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal
  if (newVal) {
    resetForm()
    if (props.isEdit && props.hospitalData) {
      Object.assign(formData, props.hospitalData)
    }
  }
})

// 监听dialogVisible变化
watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal)
})

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(formData, {
    name: ''
  })
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    loading.value = true

    if (props.isEdit) {
      await hospitalApi.updateHospital(props.hospitalData.id, formData)
      ElMessage.success('更新医院成功')
    } else {
      await hospitalApi.createHospital(formData)
      ElMessage.success('创建医院成功')
    }

    emit('success')
    handleClose()

  } catch (error) {
    console.error('保存医院失败:', error)
    ElMessage.error(error.message || '保存医院失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}

.el-form-item {
  margin-bottom: 20px;
}
</style>
